"""
Python script to simply automate creating foaf files
This versions creates a person,
gets properties that have that as a range via a SPARQL query
and asks for a value for each property

"""
#import stuff
import rdflib

rdflib.plugin.register('sparql', rdflib.query.Processor,
                       'rdfextras.sparql.processor', 'Processor')
rdflib.plugin.register('sparql', rdflib.query.Result,
                       'rdfextras.sparql.query', 'SPARQLQueryResult')
#functions
def add_data(Graph, propertylabel, propertyuri):
    data = raw_input(propertylabel+"?: ")
    Graph.add((me, propertyuri, rdflib.Literal(data)))

#Semantic SetUp
Graph = rdflib.ConjunctiveGraph()

FOAF = rdflib.Namespace("http://xmlns.com/foaf/0.1/")

#Parse Ontology
FoafOntology = rdflib.Graph()
FoafOntology.parse(FOAF)

#Create A New Person
MyGraph = rdflib.Graph()
me = rdflib.BNode()
MyGraph.add((me, rdflib.RDF.type, FOAF['Person']))
print "New Person Created"

#Query to get datatype properties and their labels (Note - Poor Inferencing Abilities in RDFlib Queries)
sparql = '''SELECT ?a ?c
WHERE {
?a <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://www.w3.org/2002/07/owl#DatatypeProperty>.
?a <http://www.w3.org/2000/01/rdf-schema#label> ?c.
?a <http://www.w3.org/2000/01/rdf-schema#domain> <http://xmlns.com/foaf/0.1/Person>.
}
'''

sparqlquery = FoafOntology.query(sparql, initNs=dict(foaf=rdflib.Namespace("http://xmlns.com/foaf/0.1/")))
for row in sparqlquery:
    propertylabel = row[1]
    propertyuri = row[0]
    add_data(MyGraph, propertylabel, propertyuri)

print MyGraph.serialize(format="pretty-xml")

#Write to File
outfile = open("Medical Record.rdf", "w")
outfile.write(MyGraph.serialize(format="pretty-xml"))
#outfile.write("Hello World")
outfile.close()

print "Written to File"


